#!/bin/sh
set -e

# Load configs
CONFIG_FILE=/etc/hassio.json

SUPERVISOR="$(jq --raw-output '.supervisor' ${CONFIG_FILE})"
HOMEASSISTANT="$(jq --raw-output '.homeassistant' ${CONFIG_FILE})"
DATA="$(jq --raw-output '.data // "/usr/share/hassio"' ${CONFIG_FILE})"

# AppArmor Support
if command -v apparmor_parser > /dev/null 2>&1 && grep hassio-supervisor /sys/kernel/security/apparmor/profiles > /dev/null 2>&1; then
    APPARMOR="--security-opt apparmor=hassio-supervisor"
else
    APPARMOR="--security-opt apparmor=unconfined"
fi

# Init supervisor
HASSIO_DATA=${DATA}
HASSIO_IMAGE_ID=$(docker inspect --format='{{.Id}}' ${SUPERVISOR})
HASSIO_CONTAINER_ID=$(docker inspect --format='{{.Image}}' hassio_supervisor || echo "")

runSupervisor() {
    docker rm --force hassio_supervisor || true
    docker run --name hassio_supervisor \
        $APPARMOR \
        --security-opt seccomp=unconfined \
        -v /var/run/docker.sock:/var/run/docker.sock \
        -v /var/run/dbus:/var/run/dbus \
        -v ${HASSIO_DATA}:/data \
        -e SUPERVISOR_SHARE=${HASSIO_DATA} \
        -e SUPERVISOR_NAME=hassio_supervisor \
        -e HOMEASSISTANT_REPOSITORY=${HOMEASSISTANT} \
        ${SUPERVISOR}
}

# Run supervisor
mkdir -p ${HASSIO_DATA}
([ "${HASSIO_IMAGE_ID}" = "${HASSIO_CONTAINER_ID}" ] && docker start --attach hassio_supervisor) || runSupervisor
